<?php
/**
 * 机器人红包定时功能
 * @author LYON
 * @version 2017/5/26
 */

class RedPacketRotbot extends ScriptBase
{
    const ROTBOT_KEY = 'rotbot:expire';
    const ROTBOT_USER_KEY = 'rotbot:user';

    /**
     * 逻辑代码
     */
    public function logic()
    {
        set_time_limit(0);
        try {
            // 连接redis
            $redis = $this->redis('default');
            $times = $redis->hGetAll(self::ROTBOT_KEY);
            if (!$times || $times['end_time'] < time() || time() < $times['start_time']) {
                $this->e('red_packet_update_error','time expire!');
                echo "expire";
                exit;
            }

            $user = $redis->get(self::ROTBOT_USER_KEY);
            $userList = explode(',', $user);
            if (empty($userList)) {
                $this->e('red_packet_update_error','no user to push');
                exit;
            }

            $list = $this->mysql('default')->find('red_packet_rotbot');
            if ($list) {
                $packet = [];
                $max = 0;
                foreach ($list as $key => $val) {
                    for($i = 1; $i <= $val['num']; $i++) {
                        array_push($packet, $val['money']);
                    }
                    $max += $val['num']; 
                }

                // 打乱红包
                shuffle($packet);

                $data = [];
                $userList = array_filter($userList);
                foreach ($userList as $key => $val) {
                    if ($max > 1) {
                        $rand_num = rand(0, $max);
                        $data[$key]['uid'] = $val;
                        $data[$key]['red_values'] = $packet[$rand_num];
                        $max --;
                    }
                }
            
                if (empty($data)) {
                    $this->e('red_packet_update_error','no data to push');
                    exit;
                }

                foreach ($data as $d) {
                    $sql = "INSERT INTO red_packet_user (uid,red_values,red_nums) 
                            VALUES ('{$d['uid']}', '{$d['red_values']}', 1) 
                            ON DUPLICATE KEY 
                            UPDATE red_values=red_values+{$d['red_values']},red_nums=red_nums+1";

                    //var_dump($sql);
                    $ret = $this->mysql('default')->query($sql);
                    if (!$ret) {
                        $this->e('insert red_packet_user error:'.$this->mysql('default')->error());
                        continue;
                    }

                    $row = $this->mysql('default')->findRow('red_packet_user',['uid'=>$d['uid']]);
                    $old = $row? $row['red_values'] : 0;
                    $now = $old + $d['red_values'];
                    $create_time = time();
                    $sql = "INSERT INTO red_packet_rotbot_log (uid,before_value,value,after_value,create_time)
                            VALUES ('{$d['uid']}', $old, '{$d['red_values']}', '$now', '$create_time')";

                    $ret = $this->mysql('default')->query($sql);
                    if (!$ret) {
                        $this->e('insert red_packet_user_log error:'.$sql);
                        continue;
                    }
                }

                echo "Finish";
            }
        } catch (Exception $e) {
            $this->e('red_packet_update_error', $e->getMessage());
        }
    }
}
?>
